import Vue from 'vue'
import Vuex from 'vuex'
import http from '@/util/http'
import createPersistedState from 'vuex-persistedstate'
Vue.use(Vuex)

export default new Vuex.Store({
  plugins: [createPersistedState({
    reducer (state) {
      return {
        cityId: state.cityId,
        cityName: state.cityName
      }
    }
  })],
  state: {
    cityName: '上海',
    cityId: 310100,
    cinemasList: [],
    isNavShow: true,
    filmList: [],
    schedulesList: [],
    dataIndex: {
      index: 0,
      old: 0
    }
  },
  getters: {
  },
  mutations: {
    changeCity (state, data) {
      state.cityName = data.name
      state.cityId = data.id
      // state.dispatch('getCinemasData', data.cityId)
    },
    changeCinemasData (state, data) {
      state.cinemasList = data
    },
    clearCityData (state) {
      state.cinemasList = []
    },
    navHide (state) {
      state.isNavShow = false
    },
    navShow (state) {
      state.isNavShow = true
    },
    // 改变影院内的电影列表
    changeFilmList (state, data) {
      state.filmList = data
    },
    clearFilmList (state) {
      state.filmList = []
    },
    // 改变当前座次
    changeSchedulesList (state, data) {
      state.schedulesList = data
    },
    clearSchedulesList (state) {
      state.schedulesList = []
    },
    changeDataIndex (state, data) {
      state.dataIndex.index = data
    },
    clearDataIndex (state) {
      state.dataIndex.old = 0
    }
  },
  actions: {
    // 当跳转到影院组件的时候，通过this.$store.dispatch('名字'，数据)进行分发，执行这个函数发送请求
    getCinemasData (state, cityId) {
      return http({
        // 这里还是要传过来的城市id
        url: `/gateway?cityId=${cityId}&ticketFlag=1&k=7710221`,
        headers: {
          'X-Host': 'mall.film-ticket.cinema.list'
        }
      }).then((res) => {
        // 最后获取数据之后再通过mutation进行记录，然后修改state提前定义的城市列表(cityList)公共值
        state.commit('changeCinemasData', res.data.data.cinemas)
      })
    }
  }
})
